<template>
    <div class="login">
        <div class="title">用户登录</div>
        <div class="content">
            <!-- 表单 -->
            <form>
                <InputGroup 
                    label="账号"
                    placeholder="请填写邮箱"
                    v-model="user.email"
                    type="text"
                />

                <InputGroup 
                    label="密码"
                    placeholder="请填写密码"
                    v-model="user.password"
                    type="password"
                />
            </form>
            <div class="btn_wrap">
                <YButton :disabled="isDisabled" @click="loginClick">登录</YButton>
            </div>
        </div>
        <div class="footer_wrap">
            <button class="register" @click="$router.push('/register')">| 注册账号 |</button>
        </div>
    </div>
</template>
<script>
import InputGroup from './../components/InputGroup';
import YButton from './../components/YButton';
import jwt_decode from 'jwt-decode';
export default {
    name:'login',
    components:{InputGroup,YButton},
    data(){
        return{
            user:{
                email:'',
                password:''
            }
        }
    },
    computed:{
        isDisabled(){//在输入框有值的时候就会触发
            if(this.user.email && this.user.password){
                // 如果有值就解开禁用
                return false
            }else{
                return true
            }

        }
    },
    methods:{
        loginClick(){
            //验证邮箱
            var reg =/^([a-zA-Z0-9._-])+@([a-zA-A0-9_-])+(\.[a-zA-Z0-9_-])+/;
            if(!reg.test(this.user.email)){
                alert('请输入合法的邮箱地址!');
                return;
            }
            // 实现登录 
            this.$axios.post('/api/users/login',this.user)
            .then(res =>{//返回中有token,
                console.log(res)

                //存储token
                const {token} = res.data;
                // 把token存储到locastorng中
                localStorage.setItem('wxToken',token);

                // 解析token
                const decode = jwt_decode(token);
                console.log(decode)
                // 把解析出来的token存入vuex中
                this.$store.dispatch('setUser',decode)

                // 在座成功后实现页面跳转
                this.$router.push('/')
            })
        }
    }
}
</script>
<style scoped>
.login{
    width: 100%;
    height: 100%;
    overflow: hidden;
    padding: 16px;
    box-sizing: border-box;
}
.title{
    margin-top: 80px;
    font-size: 22px;
    text-align: center;
}
.footer_wrap{
    position: absolute;
    left: 0;
    bottom: 16px;
    text-align: center;
    width:100%;
    color: #888;
}
.footer_wrap .register{
    font-size: 16px;
    outline: none;
    border:none;
    background: transparent;
    color: #7b8ca9;
}
</style>


